package bb.lanxing.lib.devices.bryton.bbcp;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Pair;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import bb.lanxing.lib.devices.bryton.ncs.ExtensionData;
import bb.lanxing.lib.devices.bryton.nordic.dfu.AbortedException;
import bb.lanxing.lib.devices.bryton.nordic.dfu.DeviceDisconnectedException;
import java.util.List;
import java.util.TreeMap;
import java.util.UUID;
import kotlin.UShort;

public class BbcpManager extends BleManager {
    static final String BROADCAST_PROGRESS = "com.brytonsport.bbcp.BROADCAST_PROGRESS";
    static final String BROADCAST_RESULT = "com.brytonsport.bbcp.BROADCAST_ERROR";
    private static final int PACKAGE_SENT_INTERVAL = 10;
    private static final long TIMEOUT_MS = 5000;
    private BbcpCommand mAbortedCommand;
    private boolean mAckExpected;
    private int mBncsAttrIndex;
    private BbcpManagerCallbacks mCallbacks;
    private BbcpCommand mCommand;
    private byte[] mData;
    private int mDataPackets;
    private ExtensionData mExtensionData;
    private byte[] mExtraData;
    private volatile boolean mNotificationsEnabled;
    private volatile int mPacketsSinceAck;
    private volatile int mPacketsTransfered;
    private boolean mRead;
    private volatile boolean mRequestCompleted;
    private BbcpCommand mResponse;
    public static final UUID BBCP_DATA_SERVICE_UUID = new UUID(4993760298828694925L, -7259066960687485054L);
    public static final UUID BBCP_DATA_UUID = new UUID(4993741607131022733L, -7259066960687485054L);
    public static final UUID BBCP_SERVICE_UUID = new UUID(4993778990526367117L, -7259066960687485054L);
    private static final UUID BBCP_CONTROL_POINT_UUID = new UUID(4993685532038006157L, -7259066960687485054L);
    private static final UUID BBCP_PACKET_UUID = new UUID(4993666840340333965L, -7259066960687485054L);
    private static final UUID CLIENT_CHARACTERISTIC_CONFIG = new UUID(45088566677504L, -9223371485494954757L);
    public static final UUID BNCS_DATA_SERVICE_UUID = new UUID(4993778844497479053L, -7259066960687485054L);
    private static final UUID BNCS_PACKET_UUID = new UUID(4993704223735678349L, -7259066960687485054L);
    protected static final char[] hexArray = "0123456789ABCDEF".toCharArray();
    private volatile boolean mNotified = false;
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            BbcpManager.this.loge("wait and no data is coming");
            BbcpManager.this.mErrorState = 273;
            BbcpManager.this.notifyOnGoing();
        }
    };
    private WriteRunnable mWriteRunnable = new WriteRunnable();
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt bluetoothGatt, int i, int i2) {
            BbcpManager.this._handleConnectionStateChange(bluetoothGatt, i, i2);
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            BbcpManager.this._handleServicesDiscovered(bluetoothGatt, i);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            if (BbcpManager.this.mConnectionState != -3) {
                return;
            }
            if (BbcpManager.BBCP_CONTROL_POINT_UUID.equals(bluetoothGattCharacteristic.getUuid())) {
                BbcpManager.this._handleRespone(bluetoothGatt, bluetoothGattCharacteristic);
            } else if (!BbcpManager.BBCP_PACKET_UUID.equals(bluetoothGattCharacteristic.getUuid())) {
            } else {
                BbcpManager.this._handleDataReceived(bluetoothGatt, bluetoothGattCharacteristic);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
            if (BbcpManager.this.mConnectionState != -3) {
                return;
            }
            if (!BbcpManager.BBCP_CONTROL_POINT_UUID.equals(bluetoothGattCharacteristic.getUuid())) {
                if (BbcpManager.BBCP_PACKET_UUID.equals(bluetoothGattCharacteristic.getUuid())) {
                    BbcpManager.this._handleDataWrite(bluetoothGatt, bluetoothGattCharacteristic, i);
                    return;
                } else if (!BbcpManager.BNCS_PACKET_UUID.equals(bluetoothGattCharacteristic.getUuid())) {
                    return;
                } else {
                    if (i == 0) {
                        BbcpManager.access$808(BbcpManager.this);
                        BbcpManager.this.writeAttribute(bluetoothGatt, bluetoothGattCharacteristic);
                    } else {
                        BbcpManager bbcpManager = BbcpManager.this;
                        bbcpManager.loge("write notification failed:" + i);
                        BbcpManager.this.mExtensionData = null;
                        BbcpManager.this.mBncsAttrIndex = 0;
                    }
                    BbcpManager.this.notifyOnGoing();
                    return;
                }
            }
            BbcpManager.this._handleCommandWrite(bluetoothGatt, bluetoothGattCharacteristic, i);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i) {
            if (BbcpManager.this.mConnectionState != -3) {
                return;
            }
            if (i == 0) {
                if (BbcpManager.CLIENT_CHARACTERISTIC_CONFIG.equals(bluetoothGattDescriptor.getUuid())) {
                    BbcpManager bbcpManager = BbcpManager.this;
                    boolean z = false;
                    if (bluetoothGattDescriptor.getValue()[0] == 1) {
                        z = true;
                    }
                    bbcpManager.mNotificationsEnabled = z;
                }
            } else {
                BbcpManager bbcpManager2 = BbcpManager.this;
                bbcpManager2.loge("Descriptor write error: " + i);
                BbcpManager.this.mErrorState = i | 1024;
            }
            BbcpManager.this.notifyOnGoing();
        }
    };
    private BbcpInputStream mInputStream = null;
    private short mNumberOfPacketsForAck = 0;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BbcpManager.this.mCommand == null) {
                return;
            }
            if (BbcpManager.BROADCAST_PROGRESS.equals(action)) {
                int intExtra = intent.getIntExtra("com.brytonsport.bbcp.EXTRA_DATA", 0);
                if (BbcpManager.this.mCallbacks == null) {
                    return;
                }
                BbcpManager.this.mCallbacks.onProgressUpdate(intExtra);
            } else if (BbcpManager.BROADCAST_RESULT.equals(action)) {
                BbcpManager.this.logi("set mCommand null");
                BbcpManager.this.mCommand = null;
                int intExtra2 = intent.getIntExtra("com.brytonsport.bbcp.EXTRA_DATA", 0);
                if (!BbcpManager.this.mRead) {
                    BbcpManager.this.logi("onDataSend is called");
                    if (BbcpManager.this.mCallbacks == null) {
                        return;
                    }
                    BbcpManager.this.mCallbacks.onDataSend(intExtra2);
                } else if (intExtra2 == 0) {
                    BbcpManager.this.logi("onDataReceived is called");
                    if (BbcpManager.this.mCallbacks == null) {
                        return;
                    }
                    BbcpManager.this.mCallbacks.onDataReceived(intExtra2, BbcpManager.this.mData, BbcpManager.this.mExtraData);
                } else {
                    BbcpManager.this.logi("onDataReceived is called");
                    if (BbcpManager.this.mCallbacks == null) {
                        return;
                    }
                    BbcpManager.this.mCallbacks.onDataReceived(intExtra2, null, null);
                }
            }
        }
    };

    static /* synthetic */ int access$808(BbcpManager bbcpManager) {
        int i = bbcpManager.mBncsAttrIndex;
        bbcpManager.mBncsAttrIndex = i + 1;
        return i;
    }

    public class WriteRunnable implements Runnable {
        private byte[] mBuffer;
        private BluetoothGattCharacteristic mCharacteristic;
        private BluetoothGatt mGatt;

        WriteRunnable() {
        }

        @Override
        public void run() {
            BbcpManager.this.writePackage(this.mGatt, this.mCharacteristic, this.mBuffer);
        }

        public void write(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, byte[] bArr) {
            this.mGatt = bluetoothGatt;
            this.mCharacteristic = bluetoothGattCharacteristic;
            this.mBuffer = bArr;
        }
    }

    public BbcpManager() {
        this.TAG = "BbcpManager";
        this.mCallbacks = null;
        HandlerThread handlerThread = new HandlerThread("BbcpManager");
        handlerThread.start();
        this.mAsyncLooper = handlerThread.getLooper();
        this.mAsyncHandler = new Handler(this.mAsyncLooper);
    }

    public int connect(Context context, BluetoothDevice bluetoothDevice) {
        this.mAborted = false;
        this.mAbortedCommand = null;
        this.mErrorState = 0;
        try {
            _connect(context, bluetoothDevice, this.mGattCallback, this.mReceiver);
        } catch (AbortedException | DeviceDisconnectedException e) {
            throw new RuntimeException(e);
        }
        return this.mErrorState;
    }

    public void _handleDataWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
        if (this.mAborted) {
            return;
        }
        if (i == 0) {
            if (!(this.mNumberOfPacketsForAck > 0 && this.mPacketsSinceAck == this.mNumberOfPacketsForAck)) {
                try {
                    byte[] readPackage = this.mInputStream.readPackage();
                    if (readPackage == null) {
                        logi("package data sent completely");
                    } else {
                        this.mWriteRunnable.write(this.mBluetoothGatt, bluetoothGattCharacteristic, readPackage);
                        this.mAsyncHandler.postDelayed(this.mWriteRunnable, 10L);
                    }
                } catch (BbcpValidationException e) {
                    loge(e.getMessage());
                    this.mErrorState = 264;
                }
                updateWriteProgressNotification();
            } else {
                logi("wait for ACK");
            }
        } else {
            loge("Characteristic write error: " + i);
            this.mErrorState = i | 1024;
        }
        notifyOnGoing();
    }

    public void _handleDataReceived(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        logi("receiving data");
        if (this.mRequestCompleted) {
            return;
        }
        byte[] value = bluetoothGattCharacteristic.getValue();
        logi("Value:" + bytesToHex(value));
        try {
            boolean z = false;
            BbcpData createFragment = BbcpData.createFragment(value, this.mPacketsTransfered == this.mDataPackets);
            this.mPacketsSinceAck++;
            if (createFragment.getType() == 0) {
                BbcpDataStartFragment bbcpDataStartFragment = (BbcpDataStartFragment) createFragment;
                this.mDataPackets = bbcpDataStartFragment.getFragmentCount() & UShort.MAX_VALUE;
                this.mPacketsTransfered = 0;
                this.mExtraData = bbcpDataStartFragment.getExtraData();
                int lastFragmentSize = ((this.mDataPackets - 1) * 18) + bbcpDataStartFragment.getLastFragmentSize();
                if (lastFragmentSize > 0) {
                    this.mData = new byte[lastFragmentSize];
                    logi("receiving start fragment: total count=" + this.mDataPackets + ", last size=" + (int) bbcpDataStartFragment.getLastFragmentSize());
                } else {
                    throw new BbcpValidationException("wrong data length");
                }
            } else if (createFragment.getType() == 2) {
                logi("receiving data fragment: seqNo=" + (int) createFragment.getSeqNo());
                if (this.mData == null) {
                    this.mRequestCompleted = true;
                    this.mErrorState = 266;
                } else if ((createFragment.getSeqNo() & UShort.MAX_VALUE) == this.mPacketsTransfered + 1) {
                    byte[] payload = createFragment.getPayload();
                    logi("mData length=" + String.valueOf(this.mData.length) + ",payload length=" + String.valueOf(payload.length));
                    StringBuilder sb = new StringBuilder();
                    sb.append("mPacketsSinceAck=");
                    sb.append(String.valueOf(this.mPacketsSinceAck));
                    logi(sb.toString());
                    int length = (this.mPacketsTransfered * 18) + payload.length;
                    byte[] bArr = this.mData;
                    if (length > bArr.length) {
                        throw new BbcpValidationException("wrong size of data fragment");
                    }
                    System.arraycopy(payload, 0, bArr, this.mPacketsTransfered * 18, payload.length);
                    updateReadProgressNotification();
                    this.mPacketsTransfered++;
                    if (this.mAckExpected && this.mPacketsSinceAck > 0) {
                        loge("something strange happen, receive data before onCharacteristicWrite");
                        this.mAsyncHandler.removeCallbacks(this.mRunnable);
                        this.mPacketsSinceAck = 1;
                    }
                    if (this.mNumberOfPacketsForAck > 0 && this.mPacketsSinceAck == this.mNumberOfPacketsForAck) {
                        z = true;
                    }
                    this.mAckExpected = z;
                    if (z) {
                        BluetoothGattCharacteristic characteristic = this.mBluetoothGatt.getService(BBCP_SERVICE_UUID).getCharacteristic(BBCP_CONTROL_POINT_UUID);
                        if (this.mAbortedCommand != null) {
                            logi("send ACK to abort");
                            writeCommand(this.mBluetoothGatt, characteristic, this.mAbortedCommand);
                            this.mAborted = true;
                        } else {
                            logi("send ACK to continue");
                            writeCommand(this.mBluetoothGatt, characteristic, BbcpCommand.createAckCommand(this.mCommand.getId(), this.mCommand.getSeqNo(), (byte) 6));
                            this.mAsyncHandler.removeCallbacks(this.mRunnable);
                            this.mAsyncHandler.postDelayed(this.mRunnable, 3000L);
                        }
                    }
                } else {
                    this.mRequestCompleted = true;
                    this.mData = null;
                    this.mErrorState = 266;
                }
            } else if (createFragment.getType() == 1) {
                logi("receiving end fragment");
                this.mRequestCompleted = true;
                this.mErrorState = 0;
                updateReadProgressNotification();
            }
        } catch (BbcpException e) {
            logi("bbcp error: " + e.getMessage());
            this.mErrorState = e.getErrorNumber();
        } catch (BbcpValidationException e2) {
            loge("BbcpValidationException: " + e2.getMessage());
            this.mRequestCompleted = true;
            this.mData = null;
            this.mErrorState = 264;
        } catch (DeviceDisconnectedException unused) {
            this.mErrorState = 256;
        }
        notifyOnGoing();
    }

    private void updateReadProgressNotification() {
        sendProgressBroadcast(this.mDataPackets == 0 ? 0 : (int) ((this.mPacketsTransfered * 100.0f) / this.mDataPackets), BROADCAST_PROGRESS);
    }

    private void updateWriteProgressNotification() {
        sendProgressBroadcast(this.mDataPackets == 0 ? 0 : (int) ((this.mPacketsTransfered * 100.0f) / this.mDataPackets), BROADCAST_PROGRESS);
    }

    private boolean matchCrc(byte[] bArr, byte[] bArr2) {
        byte[] checksum = BbcpData.getChecksum(bArr);
        logi("crc=" + toHexString(bArr2));
        logi("dataCrc=" + toHexString(checksum));
        if (bArr2.length != checksum.length) {
            return false;
        }
        for (int i = 0; i < bArr2.length; i++) {
            if (bArr2[i] != checksum[i]) {
                return false;
            }
        }
        return true;
    }

    public void _handleRespone(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        byte[] value = bluetoothGattCharacteristic.getValue();
        logi("handling response: " + toHexString(value));
        BbcpCommand bbcpCommand = new BbcpCommand();
        try {
            bbcpCommand.unpack(value);
            if (bbcpCommand.getType() == 2 && bbcpCommand.getStatusCode() == 6) {
                short s = this.mNumberOfPacketsForAck;
                if (s > 0) {
                    boolean z = true;
                    if (this.mAbortedCommand != null) {
                        logi("send abort action");
                        writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, this.mAbortedCommand);
                        this.mAborted = true;
                    } else {
                        if (s <= 0 || this.mPacketsSinceAck != this.mNumberOfPacketsForAck) {
                            z = false;
                        }
                        if (z) {
                            this.mPacketsSinceAck = 0;
                            this.mInputStream.mark();
                            byte[] readPackage = this.mInputStream.readPackage();
                            if (readPackage == null) {
                                loge("package data failed");
                                throw new BbcpException("package data failed", 265);
                            }
                            logi("sending data after ACK");
                            writePackage(this.mBluetoothGatt, this.mBluetoothGatt.getService(BBCP_SERVICE_UUID).getCharacteristic(BBCP_PACKET_UUID), readPackage);
                        } else {
                            loge("receive ACK at wrong time");
                        }
                    }
                }
            } else {
                this.mResponse = bbcpCommand;
            }
        } catch (BbcpException e) {
            logi("error:" + e.getMessage());
            this.mErrorState = e.getErrorNumber();
        } catch (BbcpValidationException unused) {
            this.mErrorState = 264;
        } catch (DeviceDisconnectedException unused2) {
            this.mErrorState = 256;
        }
        notifyOnGoing();
    }

    protected void _handleCommandWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
        if (i == 0) {
            if (this.mAborted) {
                logi("finish abort");
                this.mErrorState = 263;
            }
            if (this.mAckExpected) {
                this.mAsyncHandler.removeCallbacks(this.mRunnable);
                this.mPacketsSinceAck = 0;
                this.mAckExpected = false;
            }
        } else {
            loge("Characteristic write error: " + i);
            this.mErrorState = i | 1024;
        }
        notifyOnGoing();
    }

    public void setGattCallbacks(BbcpManagerCallbacks bbcpManagerCallbacks, Context context) {
        this.mCallbacks = bbcpManagerCallbacks;
        this.mContext = context;
        LocalBroadcastManager.getInstance(context).registerReceiver(this.mReceiver, makeIntentFilter());
    }

    public int bind(String str) {
        BbcpCommand readResponse = null;
        if (this.mConnectionState != -3) {
            loge("not in connected and ready");
            this.mErrorState = 256;
            return this.mErrorState;
        }
        resetState();
        logi("get service points");
        BluetoothGattCharacteristic[] servicePoints = getServicePoints();
        if (servicePoints == null) {
            loge("Device has no required service");
            return this.mErrorState;
        }
        BluetoothGattCharacteristic bluetoothGattCharacteristic = servicePoints[0];
        BluetoothGattCharacteristic bluetoothGattCharacteristic2 = servicePoints[1];
        logi("write user address: " + str);
        this.mRead = true;
        try {
            setCharacteristicNotification(this.mBluetoothGatt, bluetoothGattCharacteristic, true);
            logi("Sending command");
            this.mCommand = BbcpCommand.createUserAddressCommand((byte) 1, str);
            writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, this.mCommand);
            logi("waiting response");
            readResponse = readResponse();
            logi("response is received");
        } catch (BbcpException | BbcpValidationException | AbortedException | DeviceDisconnectedException unused) {
        }
        if (readResponse.getId() == this.mCommand.getId() && readResponse.getSeqNo() == this.mCommand.getSeqNo() && readResponse.getType() == 1) {
            byte[] payload = readResponse.getPayload();
            this.mData = payload;
            if (payload.length > 0 && payload[0] == 2) {
                logi("bind successfully");
                return this.mErrorState;
            }
            return this.mErrorState;
        }
        return this.mErrorState;
    }

    public void sendCommand(BbcpCommand bbcpCommand) {
        this.mRead = true;
        this.mCommand = bbcpCommand;
        if (this.mConnectionState != -3) {
            loge("not in connected and ready");
            this.mErrorState = 256;
            sendResultBroadcast(this.mErrorState, BROADCAST_RESULT);
            return;
        }
        resetState();
        logi("get service points");
        BluetoothGattCharacteristic[] servicePoints = getServicePoints();
        if (servicePoints == null) {
            loge("Device has no required service");
            sendResultBroadcast(267, BROADCAST_RESULT);
            return;
        }
        BluetoothGattCharacteristic bluetoothGattCharacteristic = servicePoints[0];
        BluetoothGattCharacteristic bluetoothGattCharacteristic2 = servicePoints[1];
        try {
            setCharacteristicNotification(this.mBluetoothGatt, bluetoothGattCharacteristic, true);
            logi("Sending command");
            writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, this.mCommand);
            logi("waiting response");
            BbcpCommand readResponse = readResponse();
            logi("response is received");
            if (readResponse.getId() == this.mCommand.getId() && readResponse.getSeqNo() == this.mCommand.getSeqNo() && readResponse.getType() == 1) {
                this.mData = readResponse.getPayload();
                sendResultBroadcast(0, BROADCAST_RESULT);
                return;
            }
            loge("packet is not response");
            sendResultBroadcast(271, BROADCAST_RESULT);
        } catch (BbcpException e) {
            sendResultBroadcast(e.getErrorNumber(), BROADCAST_RESULT);
        } catch (BbcpValidationException unused) {
            sendResultBroadcast(264, BROADCAST_RESULT);
        } catch (AbortedException unused2) {
            logi("aborted exception");
            sendResultBroadcast(263, BROADCAST_RESULT);
        } catch (DeviceDisconnectedException unused3) {
            sendResultBroadcast(256, BROADCAST_RESULT);
        }
    }

    public void sendFile(BbcpCommand bbcpCommand, String str, byte[] bArr, short s) {
        this.mRead = false;
        this.mCommand = bbcpCommand;
        if (this.mConnectionState != -3) {
            return;
        }
        resetState();
        this.mNumberOfPacketsForAck = s;
        this.mInputStream = new BbcpFileInputStream(str, this.mCommand, bArr);
        _sendData();
        this.mInputStream.close();
    }

    public void sendData(BbcpCommand bbcpCommand, byte[] bArr) {
        sendData(bbcpCommand, bArr, (short) 0);
    }

    public void sendData(BbcpCommand bbcpCommand, byte[] bArr, short s) {
        this.mRead = false;
        this.mCommand = bbcpCommand;
        if (this.mConnectionState != -3) {
            sendResultBroadcast(256, BROADCAST_RESULT);
            return;
        }
        resetState();
        this.mNumberOfPacketsForAck = s;
        this.mData = bArr;
        this.mInputStream = new BbcpDataInputStream(bArr, this.mCommand);
        _sendData();
    }

    private void _sendData() {
        try {
            try {
                BluetoothGattCharacteristic[] servicePoints = getServicePoints();
                if (servicePoints == null) {
                    loge("Device has no required service");
                    throw new BbcpException("Device has no required service", 262);
                }
                BluetoothGattCharacteristic bluetoothGattCharacteristic = servicePoints[0];
                BluetoothGattCharacteristic bluetoothGattCharacteristic2 = servicePoints[1];
                logi("enable notifications for control point");
                setCharacteristicNotification(this.mBluetoothGatt, bluetoothGattCharacteristic, true);
                logi("Sending command");
                writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, this.mCommand);
                logi("Waiting for response");
                BbcpCommand readResponse = readResponse();
                if (readResponse.getId() != this.mCommand.getId() || readResponse.getSeqNo() != this.mCommand.getSeqNo() || readResponse.getType() != 1) {
                    loge("packet is not response");
                    throw new BbcpException("packet is not response", 271);
                } else if (readResponse.getStatusCode() != 2) {
                    throw new RemoteBbcpException("Sending data failed", readResponse.getStatusCode() | 512);
                } else {
                    this.mResponse = null;
                    logi("sending Action command");
                    writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, BbcpCommand.createAckCommand(this.mCommand.getId(), this.mCommand.getSeqNo(), this.mNumberOfPacketsForAck));
                    synchronized (this.mLock) {
                        this.mNotified = false;
                        this.mLock.wait(5000L);
                    }
                    if (!this.mNotified) {
                        logi("write action command timeout");
                        throw new BbcpException("write action command timeout", 273);
                    }
                    byte[] readPackage = this.mInputStream.readPackage();
                    if (readPackage == null) {
                        loge("package data failed");
                        throw new BbcpException("package data failed", 265);
                    }
                    logi(String.format("sending data packages: count=%d, last fragment size=%d", Short.valueOf(this.mInputStream.getDataFragmentCount()), Byte.valueOf(this.mInputStream.getLastDataFragmentSize())));
                    this.mPacketsTransfered = 0;
                    this.mDataPackets = this.mInputStream.getDataFragmentCount();
                    writePackage(this.mBluetoothGatt, bluetoothGattCharacteristic2, readPackage);
                    logi("wait for action response");
                    int i = 0;
                    int i2 = 0;
                    while (true) {
                        try {
                            readResponse = readResponse();
                            break;
                        } catch (BbcpException unused) {
                            if (this.mErrorState != 273) {
                                break;
                            }
                            if (this.mPacketsTransfered > this.mNumberOfPacketsForAck + i) {
                                i2 = 0;
                            }
                            if (i2 == 2) {
                                break;
                            }
                            this.mPacketsTransfered -= this.mPacketsSinceAck;
                            if (i2 == 0) {
                                i = this.mPacketsTransfered;
                            }
                            this.mErrorState = 0;
                            this.mPacketsSinceAck = 0;
                            loge("re-send the packages from " + String.valueOf(this.mPacketsTransfered));
                            this.mInputStream.rewind();
                            this.mWriteRunnable.write(this.mBluetoothGatt, bluetoothGattCharacteristic2, this.mInputStream.readPackage());
                            this.mAsyncHandler.postDelayed(this.mWriteRunnable, 10L);
                            i2++;
                        }
                    }
                    if (readResponse == null) {
                        loge("null response");
                        throw new BbcpException("null response", 271);
                    } else if (readResponse.getId() != this.mCommand.getId() || readResponse.getSeqNo() != this.mCommand.getSeqNo() || readResponse.getType() != 2) {
                        loge(String.format("packet is wrong action(ACK), cmd id=%d seq=%d, response id=%d seq=%d type=%d", Byte.valueOf(this.mCommand.getId()), Byte.valueOf(this.mCommand.getSeqNo()), Byte.valueOf(readResponse.getId()), Byte.valueOf(readResponse.getSeqNo()), Byte.valueOf(readResponse.getType())));
                        throw new BbcpException("packet is not action(ACK)", 271);
                    } else if (readResponse.getStatusCode() != 3) {
                        throw new RemoteBbcpException("data invalid", readResponse.getStatusCode() | 512);
                    } else {
                        sendResultBroadcast(0, BROADCAST_RESULT);
                    }
                }
            } catch (BbcpException e) {
                sendResultBroadcast(e.getErrorNumber(), BROADCAST_RESULT);
            }
        } catch (BbcpValidationException unused2) {
            sendResultBroadcast(264, BROADCAST_RESULT);
        } catch (RemoteBbcpException e2) {
            sendResultBroadcast(e2.getErrorNumber(), BROADCAST_RESULT);
        } catch (AbortedException unused3) {
            logi("abort send data: errorState=" + String.valueOf(this.mErrorState));
            sendResultBroadcast(this.mErrorState, BROADCAST_RESULT);
        } catch (DeviceDisconnectedException unused4) {
            sendResultBroadcast(256, BROADCAST_RESULT);
        } catch (InterruptedException e3) {
            e3.printStackTrace();
        }
    }

    @SuppressLint("MissingPermission")
    public void writePackage(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, byte[] bArr) {
        logi("write package: " + toHexString(bArr));
        this.mPacketsTransfered = this.mPacketsTransfered + 1;
        this.mPacketsSinceAck = this.mPacketsSinceAck + 1;
        bluetoothGattCharacteristic.setValue(bArr);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
    }

    public void sendData(BbcpCommand bbcpCommand, TreeMap<String, String> treeMap) {
        if (this.mConnectionState != -3) {
            sendResultBroadcast(256, BROADCAST_RESULT);
            return;
        }
        logi("sending data");
        byte[] bArr = null;
        try {
            bArr = BbcpData.packAsciiPayload(treeMap);
            logi(new String(bArr));
        } catch (BbcpValidationException e) {
            loge(e.getMessage());
        }
        sendData(bbcpCommand, bArr);
    }

    public void requestData(BbcpCommand bbcpCommand) {
        requestData(bbcpCommand, (short) 0);
    }

    public void requestData(BbcpCommand bbcpCommand, short s) {
        BbcpCommand createAckCommand;
        this.mRead = true;
        this.mCommand = bbcpCommand;
        if (this.mConnectionState != -3) {
            loge("wrong connect state=" + String.valueOf(this.mConnectionState));
            sendResultBroadcast(256, BROADCAST_RESULT);
            return;
        }
        resetState();
        this.mNumberOfPacketsForAck = s;
        BluetoothGattCharacteristic[] servicePoints = getServicePoints();
        if (servicePoints == null) {
            loge("Device has no required service");
            sendResultBroadcast(267, BROADCAST_RESULT);
            return;
        }
        BluetoothGattCharacteristic bluetoothGattCharacteristic = servicePoints[0];
        BluetoothGattCharacteristic bluetoothGattCharacteristic2 = servicePoints[1];
        try {
            setCharacteristicNotification(this.mBluetoothGatt, bluetoothGattCharacteristic, true);
            logi("Sending command");
            writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, this.mCommand);
            logi("wait for response");
            BbcpCommand readResponse = readResponse();
            if (readResponse.getId() == this.mCommand.getId() && readResponse.getSeqNo() == this.mCommand.getSeqNo() && readResponse.getType() == 1) {
                if (readResponse.getStatusCode() == 6) {
                    this.mRequestCompleted = true;
                    sendResultBroadcast(this.mErrorState, BROADCAST_RESULT);
                    return;
                } else if (readResponse.getStatusCode() != 2) {
                    throw new RemoteBbcpException("Sending data failed", readResponse.getStatusCode() | 512);
                } else {
                    setCharacteristicNotification(this.mBluetoothGatt, bluetoothGattCharacteristic2, true);
                    logi("sending Action command");
                    if (this.mNumberOfPacketsForAck == 0) {
                        createAckCommand = BbcpCommand.createAckCommand(this.mCommand.getId(), this.mCommand.getSeqNo(), (byte) 3);
                    } else {
                        createAckCommand = BbcpCommand.createAckCommand(this.mCommand.getId(), this.mCommand.getSeqNo(), this.mNumberOfPacketsForAck);
                    }
                    writeCommand(this.mBluetoothGatt, bluetoothGattCharacteristic, createAckCommand);
                    synchronized (this.mLock) {
                        do {
                            if (this.mConnectionState != -3 || this.mRequestCompleted || this.mErrorState != 0) {
                                break;
                            }
                            this.mNotified = false;
                            this.mLock.wait(5000L);
                        } while (this.mNotified);
                    }
                    if (this.mAborted) {
                        throw new AbortedException();
                    }
                    if (this.mRequestCompleted) {
                        sendResultBroadcast(this.mErrorState, BROADCAST_RESULT);
                        return;
                    } else if (this.mConnectionState == 0) {
                        throw new DeviceDisconnectedException("unable to write ack command", this.mConnectionState);
                    } else {
                        if (this.mNotified) {
                            return;
                        }
                        this.mErrorState = 273;
                        sendResultBroadcast(this.mErrorState, BROADCAST_RESULT);
                        return;
                    }
                }
            }
            loge("packet is not response");
            sendResultBroadcast(271, BROADCAST_RESULT);
        } catch (BbcpException e) {
            sendResultBroadcast(e.getErrorNumber(), BROADCAST_RESULT);
        } catch (BbcpValidationException unused) {
            sendResultBroadcast(264, BROADCAST_RESULT);
        } catch (RemoteBbcpException e2) {
            sendResultBroadcast(e2.getErrorNumber(), BROADCAST_RESULT);
        } catch (AbortedException unused2) {
            logi("abort request data, errorno=" + String.valueOf(this.mErrorState));
            sendResultBroadcast(this.mErrorState, BROADCAST_RESULT);
        } catch (DeviceDisconnectedException unused3) {
            sendResultBroadcast(256, BROADCAST_RESULT);
        } catch (InterruptedException e3) {
            e3.printStackTrace();
        }
    }

    private void resetState() {
        this.mPacketsSinceAck = 0;
        this.mAborted = false;
        this.mAbortedCommand = null;
        this.mErrorState = 0;
        this.mPacketsTransfered = 0;
        this.mDataPackets = 0;
        this.mData = null;
        this.mRequestCompleted = false;
        this.mAckExpected = false;
    }

    BluetoothGattCharacteristic[] getServicePoints() {
        BluetoothGattService service = this.mBluetoothGatt.getService(BBCP_SERVICE_UUID);
        if (service == null) {
            return null;
        }
        return new BluetoothGattCharacteristic[]{service.getCharacteristic(BBCP_CONTROL_POINT_UUID), service.getCharacteristic(BBCP_PACKET_UUID)};
    }

    @SuppressLint("MissingPermission")
    private void writeCommand(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, BbcpCommand bbcpCommand) throws BbcpException, DeviceDisconnectedException, BbcpValidationException {
        byte[] pack = bbcpCommand.pack();
        this.mRequestCompleted = false;
        this.mResponse = null;
        logi("write command: value=" + toHexString(pack));
        bluetoothGattCharacteristic.setValue(pack);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
    }

    @SuppressLint("MissingPermission")
    private void setCharacteristicNotification(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, boolean z) throws BbcpException, DeviceDisconnectedException {
        if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to set notifications state", this.mConnectionState);
        }
        this.mErrorState = 0;
        this.mNotificationsEnabled = false;
        StringBuilder sb = new StringBuilder();
        sb.append(z ? "Enabling " : "Disabling");
        sb.append(" notifications...");
        logi(sb.toString());
        bluetoothGatt.setCharacteristicNotification(bluetoothGattCharacteristic, z);
        BluetoothGattDescriptor descriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
        descriptor.setValue(z ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        bluetoothGatt.writeDescriptor(descriptor);
        int i = 1;
        try {
            synchronized (this.mLock) {
                while (this.mNotificationsEnabled != z && this.mConnectionState == -3 && this.mErrorState == 0) {
                    this.mNotified = false;
                    this.mLock.wait(5000L);
                    if (!this.mNotified) {
                        if (i <= 0) {
                            break;
                        }
                        bluetoothGatt.setCharacteristicNotification(bluetoothGattCharacteristic, z);
                        BluetoothGattDescriptor descriptor2 = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
                        descriptor2.setValue(z ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                        bluetoothGatt.writeDescriptor(descriptor2);
                        i--;
                    }
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mErrorState != 0) {
            throw new BbcpException("Unable to set notifications state", this.mErrorState);
        }
        if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to set notifications state", this.mConnectionState);
        }
        if (this.mNotified) {
            return;
        }
        logi("writeDescriptor timeout");
        throw new BbcpException("writeDescriptor timeout", 272);
    }

    private BbcpCommand readResponse() throws DeviceDisconnectedException, BbcpException, AbortedException {
        this.mErrorState = 0;
        try {
            synchronized (this.mLock) {
                while (this.mResponse == null && this.mConnectionState == -3 && this.mErrorState == 0) {
                    this.mNotified = false;
                    this.mLock.wait(5000L);
                    if (!this.mNotified) {
                        break;
                    }
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
            this.mErrorState = BleManager.ERROR_EXCEPTION;
        }
        if (this.mAborted) {
            throw new AbortedException();
        }
        if (this.mErrorState != 0) {
            throw new BbcpException("read response error=", this.mErrorState);
        }
        if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to read response", this.mConnectionState);
        }
        if (!this.mNotified) {
            this.mErrorState = 273;
            logi("readResponse: wait for response timeout");
            throw new BbcpException("wait for response timeout", this.mErrorState);
        }
        return this.mResponse;
    }

    private IntentFilter makeIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BROADCAST_PROGRESS);
        intentFilter.addAction(BROADCAST_RESULT);
        return intentFilter;
    }

    public void abortTask() {
        logi("abortTask() is called");
        if (this.mConnectionState == -1) {
            this.mAborted = true;
            notifyOnGoing();
            return;
        }
        BbcpCommand bbcpCommand = this.mCommand;
        if (bbcpCommand == null) {
            return;
        }
        this.mAbortedCommand = BbcpCommand.createAckCommand(bbcpCommand.getId(), this.mCommand.getSeqNo(), (byte) 4);
    }

    public boolean sendNotification(ExtensionData extensionData) {
        if (this.mConnectionState != -3) {
            loge("not connected and ready");
            return false;
        }
        BluetoothGattCharacteristic notificationServicePoint = getNotificationServicePoint();
        if (notificationServicePoint == null) {
            loge("Device has no required service");
            return false;
        }
        synchronized (this) {
            this.mExtensionData = extensionData;
            this.mBncsAttrIndex = 0;
        }
        writeAttribute(this.mBluetoothGatt, notificationServicePoint);
        boolean z = true;
        try {
            synchronized (this.mLock) {
                while (true) {
                    if (this.mExtensionData == null || this.mConnectionState != -3 || this.mErrorState != 0) {
                        break;
                    }
                    this.mNotified = false;
                    this.mLock.wait(5000L);
                    if (!this.mNotified) {
                        loge("send notification failed, timeout");
                        z = false;
                        break;
                    }
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
            z = false;
        }
        if (this.mErrorState != 0) {
            loge("send notification failed error code=" + String.valueOf(this.mErrorState));
            return false;
        } else if (this.mConnectionState == -3) {
            return z;
        } else {
            loge("send notification failed, disconnected by reomote");
            return false;
        }
    }

    @SuppressLint("MissingPermission")
    public void writeAttribute(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        String str = "";
        String str2 = "";
        synchronized (this) {
            List<Pair<String, String>> attributes = this.mExtensionData.attributes();
            if (this.mBncsAttrIndex < attributes.size()) {
                str2 = (String) attributes.get(this.mBncsAttrIndex).first;
                str = (String) attributes.get(this.mBncsAttrIndex).second;
            }
        }
        if (str2.equals("") && str.equals("")) {
            this.mExtensionData = null;
            this.mBncsAttrIndex = 0;
            return;
        }
        try {
            byte[] pack = new BbcpNotification(this.mExtensionData.categoryID().value(), str2, str).pack();
            bluetoothGattCharacteristic.setValue(pack);
            logi("write notification: " + toHexString(pack));
            bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        } catch (BbcpValidationException e) {
            e.printStackTrace();
        }
    }

    public void notifyOnGoing() {
        synchronized (this.mLock) {
            this.mNotified = true;
            this.mLock.notifyAll();
        }
    }

    BluetoothGattCharacteristic getNotificationServicePoint() {
        BluetoothGattService service = this.mBluetoothGatt.getService(BNCS_DATA_SERVICE_UUID);
        if (service == null) {
            return null;
        }
        return service.getCharacteristic(BNCS_PACKET_UUID);
    }

    public static String bytesToHex(byte[] bArr) {
        char[] cArr = new char[(bArr.length * 3) - 1];
        for (int i = 0; i < bArr.length; i++) {
            int i2 = bArr[i] & 255;
            int i3 = i * 3;
            char[] cArr2 = hexArray;
            cArr[i3] = cArr2[i2 >>> 4];
            cArr[i3 + 1] = cArr2[i2 & 15];
            if (i != bArr.length - 1) {
                cArr[i3 + 2] = '-';
            }
        }
        return new String(cArr);
    }
}
